package com.love.netty.demo.handler.request;

import com.love.netty.enums.MsgSignFlagEnum;
import com.love.netty.util.ChannelSuperviseUtils;
import com.love.netty.util.RedisUtils;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: TextWebSocketFrameHandler
 * @Description:
 * @Author: wuj
 * @Date: 2021-07-02 16:56
 **/
@Component
@ChannelHandler.Sharable
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    private RedisUtils redisUtils;

    private static final Logger LOGGER = LoggerFactory.getLogger(TextWebSocketFrameHandler.class);

    /**
     **
      * @Description 心跳检测
      * @Date 16:06 2021/7/5
      * @Param
      * @return
     **/
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            ctx.pipeline().remove(HttpRequestHandler.class);
        }
        super.userEventTriggered(ctx, evt);
    }

    /**
     * 当从channel 时调用
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String requestMsg = msg.text();
        String[] split = requestMsg.split("-");
        //发送的消息
        String message = split[2];
        //接收人的用户id
        String toUserId = split[1];
        String fromUserId = split[0];
        String recieveKey = fromUserId + "-" + toUserId;
        //查询接收方id 对应的channel
        Channel channel = ChannelSuperviseUtils.getChannelByUserId(toUserId);
        if(channel != null){
            //发送的的用户id
            String fromId = ChannelSuperviseUtils.getFromUserIdByChannelId(channel.id().asLongText());
            LOGGER.info("服务端内容：用户 {}  发送给：{}，的消息【{}】",ctx.channel().id().asLongText(),toUserId,message);
            TextWebSocketFrame resp = new TextWebSocketFrame(message);
            channel.writeAndFlush(resp.retain());
        }else{
            LOGGER.info("离线消息");
            String key = MsgSignFlagEnum.unsign.getType()+"-"+ recieveKey;
            List<String> list = redisUtils.lRange(key, 0,-1);
            if(list != null && list.size() > 0){
                redisUtils.lpushList(key,message);
            }else{
                redisUtils.rpushList(key,message);
            }
            //保存离线消息的关系(接收人:发送人)到redis
            redisUtils.sadd(toUserId,fromUserId);

        }



    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        LOGGER.error(ctx.channel().id().asShortText(), cause);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        ChannelSuperviseUtils.removeChannel(ctx.channel());
        LOGGER.info("[ {} ]断开连接", ctx.channel().id().asShortText());
    }
}
